package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.UacThresholdMapper;
import com.csun.cmny.provider.model.domain.UacThreshold;
import com.csun.cmny.provider.model.dto.threshold.UacThresholdSaveDto;
import com.csun.cmny.provider.service.UacThresholdService;
import com.csun.cmny.util.PublicUtil;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-02-26 17:40
 * @Description: the class uac threshold service impl
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UacThresholdServiceImpl extends BaseService<UacThreshold> implements UacThresholdService {

    @Resource
    private UacThresholdMapper uacThresholdMapper;

    /**
     * show uac threshold by groupId
     *
     * @param groupId group id
     * @return the uac threshold
     */
    @Override
    public UacThreshold showByGroupId(Long groupId) {

        UacThreshold uacThreshold = new UacThreshold();
        uacThreshold.setGroupId(groupId);
        uacThreshold = uacThresholdMapper.selectOne(uacThreshold);

        return uacThreshold;
    }

    /**
     * save uac threshold
     *
     * @param uacThresholdSaveDto the uac threshold save dto
     * @param loginAuthDto        the login auth dto
     * @return the int.
     */
    @Override
    public Integer save(UacThresholdSaveDto uacThresholdSaveDto, LoginAuthDto loginAuthDto) {

        Integer result = 0;

        Preconditions.checkArgument(uacThresholdSaveDto.getBreathMax() != null,
                "呼吸上限不能为空");

        Preconditions.checkArgument(uacThresholdSaveDto.getBreathMin() != null,
                "呼吸下限不能为空");

        Preconditions.checkArgument(uacThresholdSaveDto.getHeartMax() != null,
                "心跳上限不能为空");

        Preconditions.checkArgument(uacThresholdSaveDto.getHeartMin() != null,
                "心跳下限不能为空");

        UacThreshold uacThreshold = new UacThreshold();
        uacThreshold.setGroupId(loginAuthDto.getGroupId());
        uacThreshold = uacThresholdMapper.selectOne(uacThreshold);
        if (PublicUtil.isEmpty(uacThreshold)) {
            uacThreshold = new UacThreshold();
            BeanUtils.copyProperties(uacThresholdSaveDto, uacThreshold);
            uacThreshold.setUpdateInfo(loginAuthDto);
            uacThreshold.setGroupId(loginAuthDto.getGroupId());
            result = uacThresholdMapper.insertSelective(uacThreshold);
        } else {
            BeanUtils.copyProperties(uacThresholdSaveDto, uacThreshold);
            uacThreshold.setUpdateInfo(loginAuthDto);
            result = uacThresholdMapper.updateByPrimaryKeySelective(uacThreshold);
        }

        return result;
    }
}
